<template>
  <div id="app">
    <router-view />
    <audio src="./assets/mp3/preview.mp3" ref="ordersAudio"></audio>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      websocket: null,
    }
  },
  created() {
    //页面刚进入时开启长连接
    this.initWebSocket()
  },
  destroyed: function () {
    //页面销毁时关闭长连接
    this.websocketclose();
  },
  methods: {
    run() {
      const audio = this.$refs.ordersAudio
      var t2 = 11000; // 音频的长度，确保能够完整的播放给用户
      var play = false;
      if (play) {
        return false;
      }
      audio.currentTime = 0;// 设置播放的音频的起始时间
      audio.volume = 0.5;// 设置音频的声音大小
      audio.muted = false;// 关闭静音状态
      play = true;
      setTimeout(function () {
        play = false;
        audio.muted = true;//播放完毕，开启静音状态
      }, t2);
    },
    initWebSocket() { //初始化weosocket
      const wsuri = "ws://localhost:51801/listen_new_orders"
      this.websocket = new WebSocket(wsuri);
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onclose = this.websocketclose;
    },

    websocketonopen() {
      console.log("WebSocket连接成功");
    },
    websocketonerror(e) { // 错误
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage(e) { // 数据接收
      let that = this
      console.log('订单数据', e.data);
      that.$refs.ordersAudio.play()
      setTimeout(() => {
        this.run()
      }, 100)
      this.$notify({
        title: '您有一条新的订单！',
        message: e.data,
        position: 'top-right',
        duration: 0,
        type: 'warning',
        onClick() {
        }
      });

    },

    websocketsend(agentData) { //数据发送 
      this.websock.send(agentData);
    },

    websocketclose(e) { // 关闭 
      console.log("connection closed (" + e.code + ")");
    },
  }
}
</script>
